package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.handler.exception.SpzxException;
import com.atguigu.commom.utils.ThreadLocalUtil;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.FileService;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.common.ResultCodeEnum;
import com.atguigu.spzx.model.dto.sys.LoginDto;
import com.atguigu.spzx.model.dto.sys.SysUserDto;
import com.atguigu.spzx.model.entity.sys.SysUser;
import com.atguigu.spzx.model.vo.sys.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * title:
 * author: zgl
 * date: 2023/12/26
 * description：
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private FileService fileService;

    @Override
    public LoginVo login(LoginDto loginDto) {
        //获取账号密码
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        String code = loginDto.getCode();
        String codeKey = loginDto.getCodeKey();
        //判断账号密码是否为空
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)) {
            throw new SpzxException(ResultCodeEnum.LOGIN_PARAM_ERROR);
        }
        String redisCode = redisTemplate.opsForValue().get("sys:user:code:" + codeKey);
        if (StringUtils.isEmpty(redisCode) || !code.equals(redisCode)) {
            throw new SpzxException(ResultCodeEnum.CODE_ERROR);
        }
        //删除redis里面的验证码缓存
        redisTemplate.delete("sys:user:code:" + codeKey);
        //查询数据库信息
        SysUser sysUser = sysUserMapper.findSysUserByUsername(userName);
        if (sysUser == null) {
            throw new SpzxException(ResultCodeEnum.Login_USERNAME_ERROR);
        }
        //校验密码
        //将密码加密
        String iptPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!iptPassword.equals(sysUser.getPassword())) {
            throw new SpzxException(ResultCodeEnum.Login_PASSWORD_ERROR);
        }
        redisTemplate.delete("sys:user:code:" + codeKey);
        //将用户信息缓存到redis
        //将用户密码清空  脱敏
        sysUser.setPassword("");
        //将用户信息对象转换成JSON字符串
        String json = JSON.toJSONString(sysUser);
        //生成token
        String token = IdUtil.createSnowflake(1, 1).nextIdStr();
        redisTemplate.opsForValue().set("sys:user:login:" + token, json, 7, TimeUnit.DAYS);
        //将数据包装成loginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("111111");
        return loginVo;
    }

    @Override
    public SysUser getUserInfo() {
     /*public SysUser getUserInfo(String token) {
       if (StringUtils.isEmpty(token)) {
            throw new SpzxException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        String json = redisTemplate.opsForValue().get("sys:user:login" + token);
        if (StringUtils.isEmpty(json)) {
            throw new SpzxException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        SysUser sysUser = JSON.parseObject(json.getBytes(), SysUser.class);
        return sysUser;*/
        //从本地线程变量里面获取
        return ThreadLocalUtil.get();
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("sys:user:login:" + token);
    }

    @Override
    public PageInfo<SysUser> getUserList(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        //设置参数
        PageHelper.startPage(pageNum, pageSize);
        //查询数据库
        List<SysUser> userList = sysUserMapper.getUserList(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    @Override
    public void deleteById(Long id) {
        //查询用户信息作为删除条件
        SysUser sysUser = sysUserMapper.getUserById(id);
        sysUserMapper.deleteById(id);
        //删除minio里面的文件
        if (!StringUtils.isEmpty(sysUser.getAvatar())) {
            fileService.delete(sysUser.getAvatar());
        }
    }

    @Override
    public void saveUser(SysUser sysUser) {
        //密码加密
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        //添加用户
        sysUserMapper.saveUser(sysUser);
    }

    @Override
    public void updateUser(SysUser sysUser) {
        sysUserMapper.updateUser(sysUser);
    }

    @Override
    public SysUser getUserById(Long id) {
        return sysUserMapper.getUserById(id);
    }
}
